#include "ConstantBuffer.h"
#include "D3d11Utils.h"

ConstantBuffer::ConstantBuffer()
{
	
}

ConstantBuffer* ConstantBuffer::Create(DeviceManager* pManager, int size)
{
	ConstantBuffer* pConstBuf = new ConstantBuffer();

	pConstBuf->mpDeviceManager = pManager;
	D3D11_BUFFER_DESC bd;
	bd.Usage = D3D11_USAGE_DYNAMIC;
	bd.ByteWidth = size;
	bd.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
	bd.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
	bd.MiscFlags = 0;
	
	HRESULT hr = S_OK;
	HR(hr = pConstBuf->mpDeviceManager->mpDevice->CreateBuffer( &bd, NULL, &pConstBuf->mpBuffer ));
	if(hr != S_OK)
	{
		delete pConstBuf;
		return NULL;
	}
	return pConstBuf;
}

void ConstantBuffer::Release()
{
	SAFE_RELEASE(mpBuffer);
}

void ConstantBuffer::Write(LPVOID pSource,int size)
{
	HRESULT hr = S_OK;
	D3D11_MAPPED_SUBRESOURCE subRes;
	HR( hr = mpDeviceManager->mpContext->Map(mpBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &subRes) );
	if(hr == S_OK)
	{
		memcpy_s( subRes.pData, size, pSource, size);
	}
	mpDeviceManager->mpContext->Unmap(mpBuffer,0);
}

ID3D11Buffer* ConstantBuffer::GetBufferPointer()
{
	return mpBuffer;
}